<?php 
namespace app\common\service\queue;
use think\facade\Db;
use app\bsadmin\model\Admin as AdminModel;
use app\common\model\Company as CompanyModel;
use app\common\model\CrmCustomer as CrmCustomerModel;
use app\common\model\CrmAdviserLog as CrmAdviserLogModel;
class Crm
{
    public function auto_cancel_adviser_handle()
    {
        $CrmCustomerModel=CrmCustomerModel::whereNotNull('auto_cancel_adviser_time')->whereTime('auto_cancel_adviser_time','<',time())->find();
        if ($CrmCustomerModel) {
            $admin_uid=AdminModel::where(['username'=>'adminauto33'])->value('id');
            // 启动事务
            Db::startTrans();
            $CompanyModel=CompanyModel::where(['id'=>$CrmCustomerModel->company_id])->whereNotNull('adviser_id')->lock(true)->find();
            if($CompanyModel){
                $CrmAdviserLogModel=new CrmAdviserLogModel;
                $CrmAdviserLogModel->company_id=$CompanyModel->id;
                $CrmAdviserLogModel->admin_uid=$admin_uid;
                $CrmAdviserLogModel->adviser_id=$CompanyModel->adviser_id;
                $CrmAdviserLogModel->status=0;
                $CompanyModel->adviser_id=null;
                $CrmCustomerModel->adviser_id=null;
                $CrmCustomerModel->auto_cancel_adviser_time=null;
                try {
                    $CrmCustomerModel->save();
                    $CompanyModel->save();
                    $CrmAdviserLogModel->save();
                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                }
            }else{
                Db::commit();
            }
        }
    }
}